const OutboundModel = require("../model/OutboundModel.js");

class OutboundModelController {
  constructor() {
    this.OutboundModel = new OutboundModel();
  }
// 获取出库记录
  async getOutboundList(req, res) {
    const queryParams = req.query;
    try {
      const result = await this.OutboundModel.getOutboundList(queryParams);

      return res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，获取分类列表失败。",
      });
    }
  }
  // 添加出库记录
  async addOutbound(req, res) {
    const bodyParams = req.body;
    console.log('请求体参数:', bodyParams)
            if (req.files && req.files.out_doc_pic) {
                const file = req.files.out_doc_pic;

                // 检查文件大小 (5MB限制)
                if (file.size > 5 * 1024 * 1024) {
                    return res.status(400).json({ code: 1, msg: '文件大小超过限制（最大5MB）' });
                }

                // 检查MIME类型
                const allowedImageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp'];
                if (!allowedImageTypes.includes(file.mimetype)) {
                    return res.status(400).json({ code: 1, msg: '只允许上传图片文件 (jpg, jpeg, png, gif, bmp)' });
                }

                // 检查文件扩展名
                const allowedImageExtensions = /\.(jpg|jpeg|png|gif|bmp)$/i;
                if (!allowedImageExtensions.test(file.name)) {
                    return res.status(400).json({ code: 1, msg: '只允许上传图片文件 (jpg, jpeg, png, gif, bmp)' });
                }

                // 生成唯一文件名以防止文件名冲突
                const timestamp = Date.now();
                const randomString = Math.random().toString(36).substring(2, 15);
                const fileExtension = path.extname(file.name);
                const uniqueFileName = `${timestamp}-${randomString}${fileExtension}`;

                // 确保上传目录存在
                const uploadDir = path.join("public", "uploads");
                if (!fs.existsSync(uploadDir)) {
                    fs.mkdirSync(uploadDir, { recursive: true });
                }

                const uploadPath = path.join(uploadDir, uniqueFileName); //存储路径
                const showPath = "static/uploads/" + uniqueFileName;

                // 记录文件上传时间
                const startTime = new Date();
                console.log(`开始上传收据文件: ${uniqueFileName} at ${startTime}`);

                // 移动文件到指定位置
                await file.mv(uploadPath);

                const endTime = new Date();
                const uploadDuration = (endTime - startTime) / 1000; // 转换为秒
                console.log(`收据文件上传成功: ${uniqueFileName}, 用时: ${uploadDuration}s, 大小: ${file.size} bytes`);

                // 保存文件路径到数据库
                bodyParams.out_doc_pic = showPath;
            }
    try {
      const result = await this.OutboundModel.addOutbound(bodyParams);

      return res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，添加出库记录失败。",
      });
    }
  }
  // 获取商品信息
  async getgoodsinfo(req, res) {
    try {
      const name = req.query.goods_name;
      const result = await this.OutboundModel.getgoodsinfo(name);

      return res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，获取商品信息失败。",
      });
    }
  }
  // 删除出库记录
  async deleteOutbound(req, res) {

    const out_id = req.params.id;
    try {
      const result = await this.OutboundModel.deleteOutbound(out_id);

      return res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，删除出库记录失败。",
      });
    }
  }
  // 更新出库记录
  async updateOutbound(req, res) {
    const out_id = req.params.id;
    const bodyParams = req.body;
    try {
      const result = await this.OutboundModel.updateOutbound(out_id, bodyParams);

      return res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，更新出库记录失败。",
      });
    }
  }
  // 出库管理-更新出库记录（获取数据）
  async GetupdateOutbound(req, res) {
    const out_id = req.params.id;
    try {
      const result = await this.OutboundModel.GetupdateOutbound(out_id);

      return res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，获取出库记录失败。",
      });
    }
  }
  // 添加出库详情
  async addOutboundDetail(req, res) {
    const bodyParams = req.body;
    try {
      const result = await this.OutboundModel.addOutboundDetail(bodyParams);

      return res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，添加出库详情失败。",
      });
    }
  }
  async getgoodsinfoitem(req, res) {
    try {
      const goods_id = req.query.goods_id;
      const result = await this.OutboundModel.getgoodsinfoitem(goods_id);

      return res.json({
        code: 0,
        msg: "success",
        data: result,
      });
    } catch (error) {
      console.error(error.message);
      return res.status(500).json({
        code: 1,
        msg: "服务器内部错误，获取商品信息失败。",
      });
    }
  }
}

module.exports = OutboundModelController;
